package com.digitalchina.lxnsy.activity.old;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.ConfirmOrdersAdapter;
import com.digitalchina.lxnsy.api.BusinessCart;
import com.digitalchina.lxnsy.api.BusinessOrders;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.CartVO;
import com.digitalchina.lxnsy.entity.DataMallVO;
import com.digitalchina.lxnsy.entity.OrderItemVO;
import com.digitalchina.lxnsy.entity.OrderVO;
import com.digitalchina.lxnsy.toolkit.DecimalFormatUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.MathExtend;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：确认订单
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/1/9 16:37
 * 修改备注：
 * ================================================
 */

public class ConfirmOrdersActivity extends BaseActivity {

    @Bind(R.id.expand_list_view)
    ExpandableListView expandListView;
    @Bind(R.id.confirm_orders_tv_total)
    TextView confirmOrdersTvTotal;
    @Bind(R.id.confirm_orders_tv_submit)
    TextView confirmOrdersTvSubmit;

    private TextView tvFooterGoodsAmount; // 商品金额
    private TextView tvFooterPreferentialAmount; // 优惠

    private ConfirmOrdersAdapter confirmOrdersAdapter;

    private List<CartVO> groupList = new ArrayList<>();
    private List<List<CartVO.ShoppingCartItemVOListBean>> childList = new ArrayList<>();
    private List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOListBeen;

    private DataMallVO dataMallVO;

    private OrderItemVO orderItemVO;
    private List<OrderItemVO> orderItemVOList = new ArrayList<>();
    private OrderVO orderVO;
    private List<OrderVO> orderVOList = new ArrayList<>();

    @Override
    public void setLayout() {
        setTitle("确认订单");
        setContentLayout(R.layout.activity_confirm_orders);
    }

    @Override
    public void initMember() {

        addFooterView();

        initExpandeListView();

        if (getIntent().hasExtra("DataMallVO")) {// from 立即购买 单商品
            dataMallVO = (DataMallVO) getIntent().getSerializableExtra("DataMallVO");
            CartVO cartVO = new CartVO();
            List<CartVO.ShoppingCartItemVOListBean> itemVOListBeen = new ArrayList<>();
            CartVO.ShoppingCartItemVOListBean item = new CartVO.ShoppingCartItemVOListBean();
            item.setItemId(dataMallVO.getId());
            item.setItemLogo(dataMallVO.getImages());
            item.setItemName(dataMallVO.getTitle());
            item.setItemSummary(dataMallVO.getIntroduce());
            item.setItemPrice(dataMallVO.getAmount_num());
            item.setItemQuantity("1"); // TODO 常量
            itemVOListBeen.add(item);
            cartVO.setShoppingCartItemVOList(itemVOListBeen);
            cartVO.setSupplierId(dataMallVO.getMerchant().getId());
            cartVO.setSupplierLogo(dataMallVO.getMerchant().getHeadPortrait());
            cartVO.setSupplierName(dataMallVO.getMerchant().getMerchantName());
            cartVO.setSupplierNumber(dataMallVO.getMerchant().getMobilePhone());
            cartVO.setSupplierAddress(dataMallVO.getMerchant().getFullAddress());
            groupList.add(cartVO);
            setListData(groupList);

        } else if (getIntent().hasExtra("cartList")) { // from 购物车 多商品
            groupList = (List<CartVO>) getIntent().getSerializableExtra("cartList");
            setListData(groupList);
        }

        setFooterViewContent();
    }

    /**
     * 为footer填充内容
     */
    private void setFooterViewContent() {
//        tvFooterGoodsAmount.setText(String.format("￥%s", Utils.formatPrice(getTotal())));
        tvFooterGoodsAmount.setText(String.format("￥%s", DecimalFormatUtil.getInstance().formats(getTotal())));
        tvFooterPreferentialAmount.setText(String.format("￥%s", "0.00"));
//        confirmOrdersTvTotal.setText(String.format("合计: ￥%s", Utils.formatPrice(getTotal())));
        confirmOrdersTvTotal.setText(String.format("合计: ￥%s", DecimalFormatUtil.getInstance().formats(getTotal())));
    }

    /**
     * 为ExpandListView添加FooterView
     */
    private void addFooterView() {
        View footerView = LayoutInflater.from(this).inflate(R.layout.footer_view_for_confirm_order, null);
        tvFooterGoodsAmount = (TextView) footerView.findViewById(R.id.footer_confirm_orders_tv_goods_amount);
        tvFooterPreferentialAmount = (TextView) footerView.findViewById(R.id.footer_confirm_orders_tv_preferential);
        expandListView.addFooterView(footerView);
    }

    /**
     * 初始化 ExpandListView
     */
    private void initExpandeListView() {
        confirmOrdersAdapter = new ConfirmOrdersAdapter(this, groupList, childList);
        expandListView.setAdapter(confirmOrdersAdapter);
        expandListView.setGroupIndicator(null);
        expandListView.setDividerHeight(2);
    }

    /**
     * 设置父子list
     *
     * @param groupList
     */
    private void setListData(List<CartVO> groupList) {

        childList.clear();

        for (int i = 0; i < groupList.size(); i++) {
//            List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOListBeen = groupList.get(i).getShoppingCartItemVOList();
            shoppingCartItemVOListBeen = groupList.get(i).getShoppingCartItemVOList();
            childList.add(shoppingCartItemVOListBeen);
        }

        confirmOrdersAdapter.setListData(groupList, childList);

        // 展开所有列表
        for (int i = 0; i < confirmOrdersAdapter.getGroupCount(); i++)
            expandListView.expandGroup(i);


    }

    /**
     * 获取商品的总价
     *
     * @return 总价
     */
    private String getTotal() {
        String total = "0.00";
        for (int i = 0; i < groupList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                total = MathExtend.add(total, MathExtend.multiply(childList.get(i).get(j).getItemPrice(), childList.get(i).get(j).getItemQuantity()));
            }

        }
        return String.valueOf(total);
    }

    @Override
    public void addListener() {

        // 父
        expandListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
        // 子
        expandListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                return false;
            }
        });

        confirmOrdersTvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog("请稍候...");

                isProductExpired();

//                LogUtils.e(getAllItemsID());

//                submitOrder();
            }
        });

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTipsDialog();
            }
        });
    }

    /**
     * 获取所有商品ID
     *
     * @return String
     */
    private String getAllItemsID() {
        String checkedItemsID = "";
        for (int i = 0; i < shoppingCartItemVOListBeen.size(); i++) {
            checkedItemsID += (String.format("%s,", shoppingCartItemVOListBeen.get(i).getItemId()));
        }
        if (checkedItemsID.length() < 1)
            return "";

        return checkedItemsID.substring(0, checkedItemsID.length() - 1);
    }

    @Override
    public void onBackPressed() {
        showTipsDialog();
    }

    /**
     * 确定放弃订单提交弹出框
     */
    private void showTipsDialog() {

    }

    /**
     * 商品是否已过期
     */
    private void isProductExpired() {
        BusinessOrders.isProductsExpired(this, getAllItemsID(), mHandler);
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        for (int i = 0; i < shoppingCartItemVOListBeen.size(); i++) {
            orderItemVO = new OrderItemVO();
            orderItemVO.setProductId(shoppingCartItemVOListBeen.get(i).getItemId());//商品ID
            orderItemVO.setProductType("0");
            orderItemVO.setSn("");//编号
            orderItemVO.setProductName(shoppingCartItemVOListBeen.get(i).getItemName());//商品名称
            orderItemVO.setProductDesc(shoppingCartItemVOListBeen.get(i).getItemSummary());//商品描述
            orderItemVO.setPrice(shoppingCartItemVOListBeen.get(i).getItemPrice());//商品价格
            orderItemVO.setTotalPrice(MathExtend.multiply(shoppingCartItemVOListBeen.get(i).getItemPrice(), shoppingCartItemVOListBeen.get(i).getItemQuantity()));//总价
            orderItemVO.setTotalPriceReal(MathExtend.multiply(shoppingCartItemVOListBeen.get(i).getItemPrice(), shoppingCartItemVOListBeen.get(i).getItemQuantity()));//实付总价
            orderItemVO.setProductImg(shoppingCartItemVOListBeen.get(i).getItemLogo());//商品图片
            orderItemVO.setQuantity(shoppingCartItemVOListBeen.get(i).getItemQuantity());//数量
            orderItemVO.setProductUrl(URL.URL_PRODUCT_DETAILS_COLLECT_URL + shoppingCartItemVOListBeen.get(i).getItemId());//商品链接
            orderItemVOList.add(orderItemVO);
        }

        orderVO = new OrderVO();
        orderVO.setPickupAddress(groupList.get(0).getSupplierAddress());//取货地址
        orderVO.setPaymentType(Constant.PAYMENT_TYPE_ON_LINE);
        orderVO.setShippingType(Constant.SHIPPING_TYPE_POST);//发货类型：不需发货，自提，邮寄
        orderVO.setSellerId(groupList.get(0).getSupplierId());//卖家
        orderVO.setSellerName(groupList.get(0).getSupplierName());//卖家名称
        orderVO.setSellerPhone(groupList.get(0).getSupplierNumber());//卖家电话
        orderVO.setSellerLogo(groupList.get(0).getSupplierLogo());//卖家logo
        orderVO.setSellerAddress(groupList.get(0).getSupplierAddress());//卖家地址
        orderVO.setOrderItemVOList(orderItemVOList);//订单项
        orderVO.setTotalPriceOrigin(getTotal());//应收总价
        orderVO.setTotalPriceReal(getTotal());//实收总价
        orderVOList.add(orderVO);

        BusinessOrders.generateOrders(this, JSON.toJSONString(orderVOList, true), mHandler);
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_GENERATE_ORDERS_SUCCESS:
                        dismissDialog();
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GENERATE_ORDERS_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_IS_PRODUCTS_EXPIRED_SUCCESS:
                        String isExpired = FastJsonUtil.getString(msg.obj.toString(), "data");
                        if (isExpired != null && isExpired.equals("true")) {

                            submitOrder();
                        } else {
                            dismissDialog();
                            showToast("部分商品已过期，请重新购买");
                        }
                        break;
                    case MSG.MSG_IS_PRODUCTS_EXPIRED_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        List<String> orderNoList = FastJsonUtil.getListBean(object.toString(), "body", "orderNoList", String.class);
        String orderNo = orderNoList != null ? orderNoList.get(0) : "";
        if (getIntent().hasExtra("cartList")) {// 来自购物车
            BusinessCart.removeShoppingByOrderNos(this, orderNo, mHandler);//TODO 多商家的话需要修改
        }
        if (orderVO == null)
            return;
        //TODO 支付暂时由PC端处理 代码还是要滴!
//        OrderDisplayVO orderDisplayVO = new OrderDisplayVO();
//        orderDisplayVO.setOrderNo(orderNo);
//        orderDisplayVO.setTotalPriceOrigin(orderVO.getTotalPriceOrigin());
//        orderDisplayVO.setTotalPriceReal(orderVO.getTotalPriceReal());
//        GotoUtil.gotoActivity(ConfirmOrdersActivity.this, WXPayEntryActivity.class, true, "OrderDisplayVO", orderDisplayVO);
        GotoUtil.gotoActivity(ConfirmOrdersActivity.this, CashierDeskTipsActivity.class, true);
    }

    @Override
    public void rightOnClick() {

    }

}
